import re
import urllib
import wx
import optionVar


class OutputCtrl(wx.TextCtrl):
	def __init__(self, parent, font=''):
		self.font = font
		text = ("")
		wx.TextCtrl.__init__(self, parent, -1,
									text,
									wx.Point(0, 0),
									wx.Size(150, 90),
									wx.TE_MULTILINE| wx.TE_READONLY|wx.TE_RICH2|wx.TE_NOHIDESEL)

		# ----- Appearance ----- #
		# Is there no way to change Tab width?
		if optionVar.hasOption('Output_BGColour'):
			self.BackgroundColour = optionVar.getOption('Output_BGColour')
		else:
			self.BackgroundColour = '#DAF5F5'
		if optionVar.hasOption('Output_FontColour'):
			self.fontColour = optionVar.getOption('Output_FontColour')
		else:
			self.fontColour = '#000000'
		self.SetTextColour(self.fontColour)
		
		self.SetFont(self.font)
		self.SetBackgroundColour(self.BackgroundColour)
	
	def outputFromThread(self, event):
		self.AppendToOutput(event.output)
		
	def appendText(self, text):
		# Crop unnecessary part
		colStart = -1
		outputText = ''
		match = re.match('\(\:[0-9]+\)\s', text)
		if match:
			startPos = match.end()
			endPos = 0
			if urllib.quote(text[-1])=='%00':
				endPos = -1
				if text[-2]=='\n':
					endPos = -2
			if text[startPos:].startswith(': '):
				startPos += 2
				outputText = text[startPos:endPos]
			else:
				colStart = self.GetLastPosition()
				outputText ='// ' +  text[startPos:endPos] + ' //\n'
		else:
			#return value? sometimes this gets 0
			#'// WARNING: unknown result type'
			#'// ERROR: unknown maya error'
			#outputText = string.rstrip(text)
			print '(AppendToOutput)',
			print 'Return value from Maya. always unknown maya error: ' + text
		
		# output
		self.SetInsertionPointEnd()
		self.WriteText(outputText.replace('\t', '    '))#tab replaced to space
		#self.WriteText(outputText)
		if not colStart == -1:
			if outputText.startswith('// Error :'):
				textColor=wx.TextAttr("RED")
			elif outputText.startswith('// Result :'):
				textColor=wx.TextAttr("BLUE")
			elif outputText.startswith('// Info :'):
				textColor=wx.TextAttr(wx.Colour(0,128,0))
			else:
				# I have never seen this
				textColor=wx.TextAttr(wx.Colour(255,255,255))
			self.SetStyle(colStart,
						  self.GetLastPosition(), textColor)
			
	# ----- Appearance ----- #
	def GetFont(self):
		return self.font
	
	def GetTextColour(self):
		return self.fontColour
	
	def GetColour(self):
		return self.BackgroundColour
	
	def SetFont(self, newFont):
		self.font = newFont
		wx.TextCtrl.SetFont(self, self.font)
		
	def SetTextColour(self, col):
		self.fontColour = col
		self.SetDefaultStyle(wx.TextAttr(self.fontColour,
										 self.BackgroundColour)
							 )
	
	def SetColour(self, col):
		self.BackgroundColour = col
		self.SetBackgroundColour(col)
		self.SetDefaultStyle(wx.TextAttr(self.fontColour,
										 self.BackgroundColour)
							 )
